package fr.cephb.joperon.core.types.bindings;

import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

import fr.cephb.berkeley.baseapi.bindings.AbstractTupleBinding;
import fr.cephb.joperon.core.types.Fid;

public class FidBinding
	extends AbstractTupleBinding<Fid>
	{
	@Override
	public Fid entryToObject(TupleInput input)
		{
		byte array[]=new byte[Fid.getLength()];
		try
			{
			if(input.read(array)!=array.length) throw new IndexOutOfBoundsException();
			}
		catch(Exception err)
			{
			throw new RuntimeException(err);
			}
		//ignore end of string
		int c=input.readUnsignedByte();
		if(c!=(byte)0) throw new IllegalArgumentException(
				"Expected a '\\0' after FID. \""+new String(array)+"\" byte:"+c);
		return new Fid(array);
		}
	
	@Override
	public void objectToEntry(Fid fid, TupleOutput output)
		{
		try	{
			output.write(fid.getBytes());
			}
		catch(Exception err)
                        {
                        throw new RuntimeException(err);
                        }

		//write end of string '\0'
		output.writeUnsignedByte((byte)0);
		}
	}
